package lishizheng.demo01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

//练习Thread，实现多线程下载图片
public class TestThread2 implements Runnable {

    private String url; //网络图片地址
    private String name; //保存的文件名

    public TestThread2(String url, String name){
        this.url = url;
        this.name = name;
    }

    //下载图片线程的执行体
    @Override
    public void run() {
        WebDownLoader webDownLoader = new WebDownLoader();
        webDownLoader.downloader(url,name);
        System.out.println("已下载文件名为：" + name + "的图片");
    }


    public static void main(String[] args) {
        //确保图片ulr是正确的
        TestThread2 t2 = new TestThread2("https://img-blog.csdnimg.cn/20210228094648502.png","我的博客图片02.png");
        TestThread2 t3 = new TestThread2("https://img-blog.csdnimg.cn/20210303104522231.png","我的博客图片03.png");

        //一份资源
        TestThread2 t1 = new TestThread2("https://img-blog.csdnimg.cn/20210210194321356.png","我的博客图片01.png");
        //多个代理
        new Thread(t1,"azheng").start();
        new Thread(t1,"lishizheng").start();
        new Thread(t1,"阿正的梦工坊").start();
    }
}

//下载器
class  WebDownLoader{
    //下载方法
    public void downloader(String  url, String  name){
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name)); //调用FileUtils类中的copyURLToFile方法实现下载
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常：downloader方法出现问题");
        }
    }
}
